<template>
  <div>
    <!-- 图片预览 -->
    <el-image-viewer
      v-if="dialogVisible"
      :url-list="[dialogImageUrl]"
      :on-close="
        () => {
          dialogVisible = false;
        }
      "
      :hide-on-click-modal="true"
    ></el-image-viewer>
    <el-upload
      ref="FileUpload"
      :data="{ path: path }"
      :name="name"
      :action="action === '' ? $baseServer + '/upload/files' : action"
      :file-list.sync="fileList"
      :multiple="false"
      :on-preview="filePreview"
      :before-upload="beforeUpload"
      :on-success="uploadSuccess"
      :on-remove="imgRemove"
      :accept="acceptType"
    >
      <el-button type="primary">{{ btnName }}</el-button>
    </el-upload>
  </div>
</template>

<script>
import ElImageViewer from "element-ui/packages/image/src/image-viewer";
export default {
  name: "FileUpload",
  props: {
    // 上传图片路径
    value: { type: String, default: "" },
    // 表单名称
    name: { type: String, default: "filename" },
    // 上传接口地址
    action: { type: String, default: "" },
    // 上传文件路径，可为空
    path: { type: String, default: "" },
    // 上传文件大小限制，单位：kb（默认10mb）
    limitSize: { type: Number, default: 10 * 1024 },
    acceptType: {
      type: String,
      default:
        ".jpg,.png,.gif,.wepb,.jpeg,.pdf,.doc,.txt,.zip,.rar,.docx,.xlsx,.xls,.xlsm,.ppt",
    },
    btnName: { type: String, default: "附件上传" },
  },
  components: {
    ElImageViewer,
  },
  data() {
    return {
      fileList: [],
      // 图片预览
      dialogVisible: false,
      dialogImageUrl: "",
    };
  },
  mounted() {
    this.loadFile();
  },
  methods: {
    loadFile() {
      this.fileList = [];
      if (this.value != "") {
        let fileArr = JSON.parse(this.value);
        this.fileList = fileArr;
      }
    },
    // 文件预览
    filePreview(res) {
      const fileUrl = res.response ? res.response.data[0].fileUrl : res.url;
      const fileExtend = fileUrl.split(".").pop().toLowerCase();
      if (["jpg", "jpeg", "png", "wepb", "gif"].includes(fileExtend)) {
        this.dialogVisible = true;
        this.dialogImageUrl = this.$baseServer + fileUrl;
      } else {
        window.open(this.$baseServer + fileUrl);
      }
    },
    // 文件格式和大小判断
    beforeUpload(file) {
      let isRightSize = file.size / 1024 < this.limitSize;
      const FileExt = file.name.replace(/.+\./, "");

      if (!isRightSize) {
        let sizeStr = this.limitSize + "KB";
        if (this.limitSize >= 1024) {
          sizeStr = this.limitSize / 1024 + "MB";
        }
        this.$message.error("文件大小超过 " + sizeStr);
      }
      const isAccept = this.acceptType.split(",").includes("." + FileExt);

      if (!isAccept) {
        this.$message.error("请选择正确的格式的文件！");
      }
      return isRightSize && isAccept;
    },
    uploadSuccess(res, file, fileList) {
      this.setUploadData(fileList);
    },
    setUploadData(fileList) {
      let fileArr = [];
      let resArr = this.extractFileData(fileList);
      fileArr = JSON.stringify(
        resArr.map((item) => {
          return {
            name: item.fileOldName,
            url: item.fileUrl,
          };
        })
      );
      this.$emit("input", fileArr);
    },
    extractFileData(jsonArray) {
      let fileDataArray = [];
      jsonArray.forEach((item) => {
        if (
          item.response &&
          item.response.data &&
          Array.isArray(item.response.data)
        ) {
          item.response.data.forEach((fileData) => {
            fileDataArray.push(fileData);
          });
        } else {
          fileDataArray.push({
            fileOldName: item.name,
            fileUrl: item.url,
          });
        }
      });

      return fileDataArray;
    },
    imgRemove(file, fileList) {
      this.setUploadData(fileList);
    },
  },
};
</script>

<style lang="scss" scoped>
.el-image-viewer__wrapper {
  z-index: 9999 !important; /* 设置为你希望的值 */
}
</style>
